﻿#$language = "Python"
#$interface = "1.0"

import os
import time
import binascii

LOG_PATH = 'D:\\_logs\\SecureCRT'

_g_obj = None

class Log():
    _log_file = ''
    def __init__(self, head=' '*6):
        self.head = head
        self._set_log_name()

    def _set_log_name(self):
        if not os.path.exists(LOG_PATH): 
            os.makedirs(LOG_PATH)
        log_name = time.strftime('crt_log_%Y%m%d.txt', time.localtime())
        self._log_file = LOG_PATH + '\\' + log_name
        return None

    def w(self, msg, head_enable=True, end='\n', head=None):
        if head_enable and head is None:
            head = self.head
        elif not head_enable:
            head = ''

        if msg != '':
            file_object = open(self._log_file, 'a')
            lines = msg.splitlines()
            if len(lines) > 1:
                last_line = lines.pop()
                for line in lines:
                    file_object.write(head + line + '\n')
                file_object.write(head + last_line + end)
            else:
                file_object.write(head + msg.strip() + end)
            file_object.close()
        return None

    def ascii(self, msg):
        ascii_list = []
        for var in msg:
            ascii_list.append(binascii.b2a_hex(var))
        self.w(' '.join(ascii_list))

    def de_ascii(self, msg):
        str_list = []
        for var in msg.split():
            if var == '00' or int(var, 16) < 32 or int(var, 16) >= 127:
                continue
            else:
                str_list.append(chr(int(var, 16)))
        if len(str_list) > 0:
            self.w(''.join(str_list), head='decode: ')

def log_start(start_filie):
    time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    msgs = ['']
    msgs.append('=' * 60)
    msgs.append(time_stamp)
    msgs.append(start_filie)
    msgs.append('=' * 60)

    log = Log('')
    log.w('\n'.join(msgs))
    del log

    return None

def _set_global_obj(obj):
    global _g_obj
    if obj is not None:
        _g_obj = obj
    return None

def pop_info(msg, obj=None):
    _set_global_obj(obj)
    _g_obj.Dialog.MessageBox('>'+msg+'<', 'Information', 64 | 0)
    return None

def pop_warning(msg, obj=None):
    _set_global_obj(obj)
    _g_obj.Dialog.MessageBox(msg, 'Waring', 48 | 0)
    return None

def pop_error(msg, obj=None):
    _set_global_obj(obj)
    _g_obj.Dialog.MessageBox(msg, 'Error', 16 | 0)
    return None

def sleep(times):
    time.sleep(times)
